<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>患者排队系统 - 医院排队叫号系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .content {
            padding: 40px;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .form-section h3 {
            color: #333;
            margin-bottom: 15px;
            font-size: 1.3em;
            border-left: 4px solid #4CAF50;
            padding-left: 15px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: bold;
        }

        .form-group select,
        .form-group input {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        .form-group select:focus,
        .form-group input:focus {
            outline: none;
            border-color: #4CAF50;
        }

        .btn {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            padding: 15px 30px;
            border: none;
            border-radius: 8px;
            font-size: 18px;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
            margin-top: 20px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(76, 175, 80, 0.4);
        }

        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .queue-status {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 25px;
            margin-top: 30px;
            border-left: 5px solid #4CAF50;
        }

        .queue-status h3 {
            color: #333;
            margin-bottom: 15px;
            border: none;
            padding: 0;
        }

        .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .status-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .status-card .number {
            font-size: 2em;
            font-weight: bold;
            color: #4CAF50;
            margin-bottom: 5px;
        }

        .status-card .label {
            color: #666;
            font-size: 0.9em;
        }

        .current-queue {
            background: #e8f5e8;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
            text-align: center;
        }

        .current-queue .queue-number {
            font-size: 3em;
            font-weight: bold;
            color: #4CAF50;
            margin-bottom: 10px;
        }

        .current-queue .patient-name {
            font-size: 1.5em;
            color: #333;
            margin-bottom: 5px;
        }

        .current-queue .status-text {
            color: #666;
            font-size: 1.1em;
        }

        .success-message {
            background: #d4edda;
            color: #155724;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            border: 1px solid #c3e6cb;
        }

        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            border: 1px solid #f5c6cb;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 10px;
            }
            
            .header {
                padding: 20px;
            }
            
            .header h1 {
                font-size: 2em;
            }
            
            .content {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🏥 患者排队系统</h1>
            <p>请选择科室和医生，填写您的信息进行排队</p>
        </div>

        <div class="content">
            <!-- 排队表单 -->
            <div class="form-section">
                <h3>📝 排队信息</h3>
                <form id="queueForm">
                    <div class="form-group">
                        <label for="department">选择科室：</label>
                        <select id="department" name="department" required>
                            <option value="">请选择科室</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="doctor">选择医生：</label>
                        <select id="doctor" name="doctor" required disabled>
                            <option value="">请先选择科室</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="patientName">患者姓名：</label>
                        <input type="text" id="patientName" name="patientName" required placeholder="请输入患者姓名">
                    </div>

                    <div class="form-group">
                        <label for="patientPhone">联系电话：</label>
                        <input type="tel" id="patientPhone" name="patientPhone" required placeholder="请输入联系电话">
                    </div>

                    <button type="submit" class="btn" id="submitBtn">
                        🎫 立即排队
                    </button>
                </form>
            </div>

            <!-- 成功/错误消息 -->
            <div id="messageArea"></div>

            <!-- 当前排队状态 -->
            <div class="queue-status">
                <h3>📊 当前排队状态</h3>
                <div id="queueStatusContent">
                    <div class="loading">正在加载排队状态...</div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let departments = [];
        let doctors = [];

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadDepartments();
            loadQueueStatus();
            
            // 每30秒更新一次排队状态
            setInterval(loadQueueStatus, 30000);
        });

        // 加载科室列表
        async function loadDepartments() {
            try {
                const response = await fetch('/api/departments');
                departments = await response.json();
                
                const departmentSelect = document.getElementById('department');
                departmentSelect.innerHTML = '<option value="">请选择科室</option>';
                
                departments.forEach(dept => {
                    const option = document.createElement('option');
                    option.value = dept.id;
                    option.textContent = dept.name;
                    departmentSelect.appendChild(option);
                });
            } catch (error) {
                console.error('加载科室失败:', error);
                showMessage('加载科室信息失败，请刷新页面重试', 'error');
            }
        }

        // 加载医生列表
        async function loadDoctors() {
            try {
                const response = await fetch('/api/doctors');
                doctors = await response.json();
                
                const departmentId = document.getElementById('department').value;
                const doctorSelect = document.getElementById('doctor');
                
                if (!departmentId) {
                    doctorSelect.innerHTML = '<option value="">请先选择科室</option>';
                    doctorSelect.disabled = true;
                    return;
                }
                
                const filteredDoctors = doctors.filter(doctor => doctor.departmentId == departmentId);
                
                doctorSelect.innerHTML = '<option value="">请选择医生</option>';
                filteredDoctors.forEach(doctor => {
                    const option = document.createElement('option');
                    option.value = doctor.id;
                    option.textContent = `${doctor.name} - ${doctor.title}`;
                    doctorSelect.appendChild(option);
                });
                
                doctorSelect.disabled = false;
            } catch (error) {
                console.error('加载医生失败:', error);
                showMessage('加载医生信息失败，请重试', 'error');
            }
        }

        // 科室选择变化时加载对应医生
        document.getElementById('department').addEventListener('change', loadDoctors);

        // 提交排队表单
        document.getElementById('queueForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const submitBtn = document.getElementById('submitBtn');
            const originalText = submitBtn.textContent;
            
            submitBtn.disabled = true;
            submitBtn.textContent = '正在排队...';
            
            try {
                const formData = new URLSearchParams();
                formData.append('departmentId', document.getElementById('department').value);
                formData.append('doctorId', document.getElementById('doctor').value);
                formData.append('patientName', document.getElementById('patientName').value);
                formData.append('patientPhone', document.getElementById('patientPhone').value);
                
                const response = await fetch('/api/queue', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: formData.toString()
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showMessage(`排队成功！您的排队号码是：${result.queueNumber}`, 'success');
                    document.getElementById('queueForm').reset();
                    document.getElementById('doctor').disabled = true;
                    loadQueueStatus(); // 刷新排队状态
                } else {
                    showMessage(result.message || '排队失败，请重试', 'error');
                }
            } catch (error) {
                console.error('排队失败:', error);
                showMessage('排队失败，请检查网络连接后重试', 'error');
            } finally {
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        });

        // 加载排队状态
        async function loadQueueStatus() {
            try {
                const [currentResponse, statsResponse] = await Promise.all([
                    fetch('/api/queue/current'),
                    fetch('/api/queue/stats')
                ]);
                
                const currentData = await currentResponse.json();
                const statsData = await statsResponse.json();
                
                displayQueueStatus(currentData, statsData);
            } catch (error) {
                console.error('加载排队状态失败:', error);
                document.getElementById('queueStatusContent').innerHTML = 
                    '<div class="error-message">加载排队状态失败</div>';
            }
        }

        // 显示排队状态
        function displayQueueStatus(currentData, statsData) {
            const content = document.getElementById('queueStatusContent');
            
            let html = '';
            
            // 当前叫号信息
            if (currentData.current && currentData.current.queueNumber !== "无") {
                html += `
                    <div class="current-queue">
                        <div class="queue-number">${currentData.current.queueNumber}</div>
                        <div class="patient-name">${currentData.current.patientName}</div>
                        <div class="status-text">请${currentData.current.queueNumber}号患者到诊室就诊</div>
                    </div>
                `;
            } else {
                html += `
                    <div class="current-queue">
                        <div class="queue-number">--</div>
                        <div class="patient-name">暂无患者</div>
                        <div class="status-text">当前没有患者在就诊</div>
                    </div>
                `;
            }
            
            // 统计信息
            html += `
                <div class="status-grid">
                    <div class="status-card">
                        <div class="number">${currentData.waiting || 0}</div>
                        <div class="label">等待人数</div>
                    </div>
                    <div class="status-card">
                        <div class="number">${currentData.estimatedWait || 0}</div>
                        <div class="label">预计等待(分钟)</div>
                    </div>
                    <div class="status-card">
                        <div class="number">${(statsData.today && statsData.today.total) || 0}</div>
                        <div class="label">今日总数</div>
                    </div>
                    <div class="status-card">
                        <div class="number">${(statsData.today && statsData.today.completed) || 0}</div>
                        <div class="label">已完成</div>
                    </div>
                </div>
            `;
            
            content.innerHTML = html;
        }

        // 显示消息
        function showMessage(message, type) {
            const messageArea = document.getElementById('messageArea');
            const className = type === 'success' ? 'success-message' : 'error-message';
            
            messageArea.innerHTML = `<div class="${className}">${message}</div>`;
            
            // 5秒后自动隐藏消息
            setTimeout(() => {
                messageArea.innerHTML = '';
            }, 5000);
        }
    </script>
</body>
</html>